use crate::helpers::{count_ttr, DatabaseConnection};
use anyhow::{anyhow, Result};
use matrix_sdk::ruma::events::room::message::RoomMessageEventContent;
use matrix_sdk::{room::Joined, ruma::events::room::message::OriginalSyncRoomMessageEvent, Client};
use std::ops::Deref;
use uuid::Uuid;

pub async fn count_unread_time(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Joined,
    _client: Client,
    db: DatabaseConnection,
) -> Result<()> {
    log::info!("counting unread time");
    let matrix_id = ev.sender.to_string();
    let user_id = get_user_id(matrix_id, &db).await.unwrap();
    if let Some(word_count) = count_time_db(user_id, &db).await? {
        let content = {
            if word_count.gt(&0) {
                let time = count_ttr(Some(word_count)).unwrap();
                RoomMessageEventContent::text_markdown(format!("Unread time: {time}"))
            } else {
                RoomMessageEventContent::text_markdown("No unread posts!")
            }
        };
        room.send(content, None).await?;
    }
    Ok(())
}

async fn get_user_id(matrix_id: String, db: &DatabaseConnection) -> Result<Uuid> {
    let rows = db
        .lock()
        .await
        .deref()
        .query("SELECT id FROM users WHERE matrix_id = $1", &[&matrix_id])
        .await?;
    if let Some(row) = rows.get(0) {
        Ok(row.get(0))
    } else {
        Err(anyhow!("user_id get error"))
    }
}
async fn count_time_db(user_id: Uuid, db: &DatabaseConnection) -> Result<Option<i64>> {
    let rows = db
    .lock()
    .await
    .deref()
        .query(
            "SELECT COALESCE(SUM(word_count), 0) as total FROM userposts WHERE read = false AND user_id = $1",
            &[&user_id],
        )
        .await?;
    if let Some(row) = rows.get(0) {
        Ok(Some(row.get(0)))
    } else {
        Ok(None)
    }
}
